import React from 'react'
import './css/app.scss'
import '../static/js/flexible.min.js'
import '../static/js/hidpi-canvas.min.js'
import axios from 'axios'
import enableInlineVideo from 'iphone-inline-video'
import { OPTION, POSTER_BG, BTN } from './config/index'

const wx = require('weixin-js-sdk')

const bgColor = ['#92e893', '#f99533', '#3d8ae1']

const siteYes = 'http://qiniu.yazhouqingnian.com/18-12-10/4970436.jpg'
const siteNo = 'http://qiniu.yazhouqingnian.com/18-12-10/76671490.jpg'
const siteBg = 'http://qiniu.yazhouqingnian.com/18-12-10/40858288.jpg'
const siteFoot = 'http://qiniu.yazhouqingnian.com/18-12-10/22982239.jpg'
const next = 'http://qiniu.yazhouqingnian.com/18-12-10/73673619.jpg'
const videoResource = 'http://qiniu.yazhouqingnian.com//ndx/video/nd_x264_3.mp4'

const loadBg = 'http://qiniu.yazhouqingnian.com/18-12-11/32699328.jpg'

const configUrl = 'https://www.yazhouqingnian.com/api/nd-h5/?action=jsticket'

const pauseTime = [18, 36, 51, 69, 87]
// const pauseTime = [1, 2, 3, 4, 5]

const inlineStyles = {
  objectFit: 'cover',
  float: 'left',
  width: '100vw',
  height: '100vh',
}

const getPixelRatio = function (context) {
  var backingStore = context.backingStorePixelRatio ||
    context.webkitBackingStorePixelRatio ||
    context.mozBackingStorePixelRatio ||
    context.msBackingStorePixelRatio ||
    context.oBackingStorePixelRatio ||
    context.backingStorePixelRatio || 1
  return (window.devicePixelRatio || 1) / backingStore
}

export default class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      videoEle: null,
      isStop: false,
      isShowSite: false,
      isShowFood: false,
      isPlayEnd: false,
      isShowInput: false,
      isShowFooterBtn: false,
      isShowCaidan: false,
      isStarted: false,
      isShowShare: false,
      name: '',
      step: 1,    // 初始步数，总共5步
      siteStatus: '',
      foodStatus: [],
      resurce: {},
      posterBg: '',
      store: {
        1: {
          site: '',
          food: [],
        },
        2: {
          site: '',
          food: [],
        },
        3: {
          site: '',
          food: [],
        },
        4: {
          site: '',
          food: [],
        },
        5: {
          site: '',
          food: [],
        },
      },
    }
  }

  componentDidMount() {
    this.getWechatShareConfig()
    const that = this
    const videoEle = document.querySelector('video')

    // ios 9 playsinline
    enableInlineVideo(videoEle)

    videoEle.addEventListener("x5videoexitfullscreen", function () {
      console.log("exit fullscreen")
    })

    videoEle.addEventListener("x5videoenterfullscreen", function () {
      console.log("enter fullscreen")
    })

    // 监听当前播放的进度
    videoEle.addEventListener('timeupdate', function (e) {
      const { step, store } = that.state
      console.log(step)
      const time = parseInt(videoEle.currentTime, 10)
      if (time === pauseTime[0] && step === 1) {
        that.setState({
          isStop: true,
          isShowSite: true,
          resurce: OPTION[step],
        })
        videoEle.pause()
      } else if (time === pauseTime[1] && step === 2) {
        that.setState({
          isStop: true,
          isShowSite: true,
          resurce: OPTION[step],
        })
        videoEle.pause()
      } else if (time === pauseTime[2] && step === 3) {
        that.setState({
          isStop: true,
          isShowSite: true,
          resurce: OPTION[step],
        })
        videoEle.pause()
      } else if (time === pauseTime[3] && step === 4) {
        that.setState({
          isStop: true,
          isShowSite: true,
          resurce: OPTION[step],
        })
        videoEle.pause()
      } else if (time === pauseTime[4] && step === 5) {
        that.setState({
          isStop: true,
          isShowSite: true,
          resurce: OPTION[step],
        })
        videoEle.pause()
      }
    })

    // 播放结束时触发
    videoEle.addEventListener('ended', function (e) {
      that.setState({
        isPlayEnd: true,
        isShowInput: true,
      })
    })

    this.setState({
      videoEle,
    })
  }

  componentWillUnmount() {
    const { videoEle } = this.state
    videoEle.removeEventListener('x5videoexitfullscreen')
    videoEle.removeEventListener('x5videoexitfullscreen')
    videoEle.removeEventListener('timeupdate')
    videoEle.removeEventListener('ended')
  }

  onCanPlay() {
    console.log('onCanPlay')
  }

  getWechatShareConfig() {
    console.log(wx)
    axios.get(configUrl).then(res => {
      const data = res.data
      wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: data.appId, // 必填，公众号的唯一标识
        timestamp: data.timestamp, // 必填，生成签名的时间戳
        nonceStr: data.nonceStr, // 必填，生成签名的随机串
        signature: data.signature,// 必填，签名
        jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData'] // 必填，需要使用的JS接口列表
      })

      wx.ready(function () {
        // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
        // alert('config ready')

        const title = '广州很牛'
        const desc = '广州首个创意主题型展馆，现场琳琅满目的艺术作品，天马行空的创意，足以让您大开眼界'
        const link = 'https://www.yazhouqingnian.com/nd-h5/'
        const imgUrl = 'http://qiniu.yazhouqingnian.com/18-12-10/66343324.jpg'

        wx.updateTimelineShareData({ title, link, imgUrl })
        wx.updateAppMessageShareData({ title, desc, link, imgUrl })
      })

      wx.error(function (res) {
        // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
        alert('config error')
        console.log(res)
      })
    }).catch(err => {
      console.log(err)
    })
  }

  videoPlay() {
    this.state.videoEle.play()
  }

  handleKeepPlay() {
    const { foodStatus, step, store } = this.state
    if (!foodStatus.length) {
      return
    }
    store[step]['food'] = foodStatus
    this.state.videoEle.play()
    this.setState({
      isShowFood: false,
      step: step + 1,
      isStop: false,
      store,
      siteStatus: '',
      foodStatus: [],
    })
  }

  handleStartPlay() {
    this.state.videoEle.play()
    this.setState({
      isStarted: true,
    })
  }

  handleClickNext() {
    const { siteStatus, step, store } = this.state
    if (siteStatus === '') return
    store[step]['site'] = siteStatus
    this.setState({
      isShowSite: false,
      isShowFood: true,
      store,
    })
  }

  selectSite(e) {
    this.setState({
      siteStatus: e,
    })
  }

  selectFood(v) {
    let { foodStatus } = this.state
    if (v === '都没有') {
      foodStatus = ['都没有']
    } else if (foodStatus.indexOf(v) === -1 && foodStatus.indexOf('都没有') === -1) {
      foodStatus.push(v)
    } else {
      foodStatus = [v]
    }
    this.setState({
      foodStatus,
    })
  }

  genPoster() {
    this.setState({
      isShowInput: false,
    })
    const { name, store } = this.state
    if (!name.trim().length) return
    // 选了1-7个选项的，就是一个结果，选择8-12个的一个结果，13个的一个结果
    let num = 0     // 计分
    Object.values(store).forEach(item => {
      if (item.site === 'yes') {
        num++
      }
      if (item.food[0] === '都没有') return
      num += item.food.length
    })

    let posterBg = ''
    let color = ''
    if (num <= 7) {
      posterBg = POSTER_BG[0]
      color = bgColor[0]
    } else if (num > 7 && num <= 12) {
      posterBg = POSTER_BG[1]
      color = bgColor[1]
    } else {
      posterBg = POSTER_BG[2]
      color = bgColor[2]
    }
    this.setState({
      posterBg,
    })

    const that = this
    const root = document.getElementById("root")
    const canvas = document.getElementById('poster')
    const ctx = canvas.getContext('2d')
    const img = new Image()
    const ratio = parseInt(getPixelRatio(ctx))
    const width = 375 * ratio
    const height = 667 * ratio
    canvas.width = width
    canvas.height = height
    img.setAttribute("crossOrigin", 'Anonymous')
    img.src = posterBg
    img.onload = function () {
      console.log('onload')
      ctx.drawImage(img, 0, 0, width, height)
      ctx.font = "14px Microsoft YaHei"
      ctx.fillText(name.trim(), 50, 42)

      setTimeout(function () {
        let images = new Image()
        images.setAttribute("crossOrigin", 'Anonymous')
        images.setAttribute("id", 'IMG')
        images.setAttribute("style", 'position: absolute; left:0 ; top: 0; width: 100vw; object-fit: cover; z-inde: -1;')
        images.src = canvas.toDataURL("image/png")
        root.appendChild(images)
        root.setAttribute("style", 'background-color: ' + color)
        that.setState({
          isShowFooterBtn: true,
        })
      }, 0)
    }
  }

  renderBtn() {
    const {isStarted} = this.state
    return (
      <div>
        <img src={loadBg} className='load-bg' alt=""/>
        <div className='load-btn' onClick={() => this.handleStartPlay()}>开始</div>
      </div>
    )
  }

  hideShare() {
    this.setState({
      isShowShare: false,
    })
  }

  renderShare() {
    return (
      <div className='share-bg' onClick={() => this.hideShare()}>
        <div className='share-tip'>
          <p>点击右上角分享给好友</p>
          <p>或微信朋友圈</p>
        </div>
      </div>
    )
  }

  renderFood() {
    const { foodStatus, resurce, step } = this.state
    return (
      <div className='site food'>
        <img src={siteBg} className='site-bg' />
        <div className='site-title'>
          <span className='num'>{2 * step}</span><span className='total'>/10.</span>
          <div className='question'>{resurce.food.title}</div>
        </div>
        <div className='food-item'>
          {resurce.food.value.map((i, v) => {
            return (<div className='item' key={v} onClick={() => this.selectFood(i.name)}>
              <img src={i.img} />
              <p><i className={foodStatus.indexOf(i.name) > -1 ? 'active' : ''}></i>{i.name}</p>
            </div>)
          })}
        </div>
        <div className='site-foot'>
          <img src={siteFoot} className='site-foot-img' />
          <div className='site-btn' onClick={() => this.handleKeepPlay()}>
            <img src={next} />
          </div>
        </div>
      </div>
    )
  }

  renderSite() {
    const { siteStatus, resurce, step } = this.state
    return (
      <div className='site'>
        <img src={siteBg} className='site-bg' />
        <div className='site-title'>
          <span className='num'>{2 * step - 1}</span><span className='total'>/10.</span>
          <div className='question'>{resurce.site.title}</div>
        </div>
        <img src={resurce.site.img} className='site-img' />
        <div className='option'>
          <div className='option-item' onClick={() => this.selectSite('yes')}>
            <i className={siteStatus === 'yes' ? 'active' : ''}></i>
            <img src={siteYes} />
          </div>
          <div className='option-item' onClick={() => this.selectSite('no')}>
            <i className={siteStatus === 'no' ? 'active' : ''}></i>
            <img src={siteNo} />
          </div>
        </div>
        <div className='site-foot'>
          <img src={siteFoot} className='site-foot-img' />
          <div className='site-btn' onClick={() => this.handleClickNext()}>
            <img src={next} />
          </div>
        </div>
      </div>
    )
  }

  renderNameInput() {
    return (
      <div className='input'>
        <img src={siteBg} className='input-bg' />
        <div className='input-action'>
          <input className='input-name' value={this.state.name} onChange={e => {
            this.setState({ name: e.target.value })
          }} type="text" maxLength='5' placeholder='输入名字' />
          <div className='input-go' onClick={() => this.genPoster()}>GO</div>
        </div>
      </div>
    )
  }

  handleClickCaidan() {
    this.setState({
      isShowCaidan: true,
      isShowInput: false,
      isShowFooterBtn: false,
    })
    document.getElementById('IMG').setAttribute('style', 'display: none')
    // document.getElementById('video').setAttribute('style', 'display: none')
  }

  hideCaidan() {
    this.setState({
      isShowCaidan: false,
      isShowInput: false,
      isShowFooterBtn: true,
    })
    document.getElementById('IMG').setAttribute('style', 'position: absolute; left: 0; top: 0;')
    // document.getElementById('video').setAttribute('style', 'display: block')
  }

  handleshare() {
    console.log('share')
    this.setState({
      isShowShare: true,
    })
  }

  renderFootBtn() {
    return (
      <div className='footer-btn'>
        <div className='footer-btn-item' onClick={() => this.handleClickCaidan()}>
          <img src={BTN[0]} />
        </div>
        <div className='footer-btn-item' onClick={() => this.handleshare()}>
          <img src={BTN[1]} />
        </div>
      </div>
    )
  }

  render() {
    const { isShowSite, isShowShare, isPlayEnd, isStarted, isShowFood, isShowInput, isShowFooterBtn, isShowCaidan } = this.state
    return (
      <div className='app'>
        {!isPlayEnd && <video
          // controls
          id="video"
          poster='http://qiniu.yazhouqingnian.com/18-12-10/98608515.jpg'
          src={videoResource}
          preload="auto"
          webkit-playsinline="true"
          playsInline
          onClick={() => document.getElementById('video').play()}
          onCanPlay={this.onCanPlay()}
          x-webkit-airplay="allow"
          x5-video-player-type="h5" // 启用H5播放器，wechat安卓版特性
          x5-video-player-fullscreen="true"   // 全屏设置，设置为 true 是防止横屏
          x5-video-orientation="portraint"  // landscape 横屏，portraint 竖屏，默认值为竖屏
          style={inlineStyles}>
        </video>}
        <canvas id='poster' style={{ position: 'absolute', left: ' -10000px' }}></canvas>
        {!isStarted && this.renderBtn()}
        {isShowSite && this.renderSite()}
        {isShowFood && this.renderFood()}
        {isShowInput && this.renderNameInput()}
        {isShowFooterBtn && this.renderFootBtn()}
        {isShowShare && this.renderShare()}
        {isShowCaidan && <div className='wrap'>
          <img src="http://qiniu.yazhouqingnian.com/18-12-10/73517071.jpg" alt="" className='caidan' />
        </div>}
      </div>
    )
  }
}